<?php
namespace app\api\controller\product;


use app\api\controller\Api;
use app\common\product\model\ProductRule;
use app\common\product\validate\ProductRuleValidate;
use think\db\exception\DbException;
use util\Format;

class Rule extends Api
{
    public function index()
    {
        $post = $this->request->post();

        $where = [];
        // 获取field
        if (isset($post['keyword']) && !empty($post['keyword'])) $where[] = ['title', 'like', "%{$post['keyword']}%"];

        $model = new ProductRule();
        list($cfg) = Format::pagination($post);
        $pg = $model->where($where)->paginate($cfg);
        $rows = $pg->getCollection();
        foreach ($rows as $row) {
            $row->append(['spec_fields', 'spec_values']);
        }

        // 返回接口数据
        $result['list'] = $rows;
        $result['pagination'] = Format::pgResult($pg);
        return success($result, '获取数据成功');
    }

    public function all()
    {
        $where = [];
        $model = new ProductRule();
        $list = $model->where($where)->select();

        // 返回接口数据
        $result['list'] = $list;
        return success($result, '获取数据成功');
    }

    public function save()
    {
        $post = $this->request->post();
        // 创建的时候清除干扰的信息
        if (empty($post['id'])) {
            $scene = "create";
            unset($post['id']);
        } else {
            $scene = "edit";
        }

        // 验证提交
        $validate = new ProductRuleValidate();
        if (!$validate->scene($scene)->check($post)) return error([], $validate->getError());

        $model = new ProductRule();
        $user = $this->request->user;
        $post['operator_id'] = $user['id'];
        try {
            if (empty($post['id'])) {
                $model->save($post);
            } else {
                $row = $model->where('id', $post['id'])->find();
                $row->save($post);
            }

            return success([], '操作成功');
        } catch (DbException $e) {
            return error([], $e->getMessage());
        }
    }

    public function read()
    {
        $post = $this->request->post();
        // 验证提交
        $validate = new ProductRuleValidate();
        if (!$validate->scene('read')->check($post)) return error([], $validate->getError());
        $model = new ProductRule();
        $result['row'] = $model->where('id', $post['id'])->find();

        return success($result);
    }
}